package com.stars.home.activity

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Rect
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import androidx.core.net.toUri
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.animation.Transformation
import com.baidu.mapapi.map.*
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.utils.DistanceUtil
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.eazypermissions.common.model.PermissionResult
import com.eazypermissions.coroutinespermission.PermissionManager
import com.luck.picture.lib.PictureSelector
import com.qmuiteam.qmui.kotlin.onClick
import com.qmuiteam.qmui.widget.QMUIRadiusImageView
import com.stars.home.R
import com.stars.home.adapter.DynamicAdapter
import com.stars.home.adapter.OrderImgAdapter
import com.stars.home.adapter.ReceivedAdapter
import com.stars.home.base.MBActivity
import com.stars.home.config.MIntentAction
import com.stars.home.databinding.ActivityOrderDetailsBinding
import com.stars.home.inte.ChoiceData
import com.stars.home.inte.OnUploadCallback
import com.stars.home.model.GoodsImgBean
import com.stars.home.model.TechOrderDetail
import com.stars.home.model.bean.UpImgBean
import com.stars.home.utils.*
import com.stars.home.vmodel.OrderDetailsVModel
import com.trailer.base.utils.DialUtils
import com.trailer.base.utils.UiUtils
import kotlinx.coroutines.launch


/**
 *on 2022/9/23
 * 订单详情
 */
class OrderDetailsActivity : MBActivity<OrderDetailsVModel, ActivityOrderDetailsBinding>(),
    OnUploadCallback<UpImgBean> {

    // 地图View实例
    private var mMapView: MapView? = null
    private var mBaiduMap: BaiduMap? = null
    private var mBitmapDescriptorStart: BitmapDescriptor? = null

    //总距离
    var z_distance: Double = 0.0
    var latEnd: LatLng? = null

    //图片
    var recordAdapter: OrderImgAdapter?=null


    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)

        //设置进度

        vm.id = intent?.extras?.getString("id")
        vm.getInfo()

        vm.bean.observe(this) {


            initMap(it.latitude, it.longitude)
            if (it.technicianStatus == 1) {
                binding.imgOne.visibility = View.VISIBLE
            }
            if (it.technicianStatus == 2) {
                binding.imgOne.visibility = View.VISIBLE
                binding.imgTwo.visibility = View.VISIBLE
            }
            if (it.technicianStatus == 3) {
                binding.imgOne.visibility = View.VISIBLE
                binding.imgTwo.visibility = View.VISIBLE
                binding.imgThree.visibility = View.VISIBLE
            }
            if (it.technicianStatus == 4) {
                binding.imgOne.visibility = View.VISIBLE
                binding.imgTwo.visibility = View.VISIBLE
                binding.imgThree.visibility = View.VISIBLE
                binding.imgFour.visibility = View.VISIBLE
            }
            //订单跟踪
            if (null != it.technicianRecord) {

                var adapter = ReceivedAdapter()
                binding.recyclerRecord.adapter = adapter
                adapter.addData(it.technicianRecord)
            }
            //三张图片上传
            if(it.technicianStatus==3&&(it.uploadImg==0||null==it.uploadImg)){
                binding.rlImg.visibility=View.VISIBLE
                binding.butSubmit.visibility=View.GONE
                binding.butImg.visibility=View.VISIBLE
                //初始化图片
                initAdapter()

            }else{
                binding.rlImg.visibility=View.GONE
                binding.butSubmit.visibility=View.VISIBLE
                binding.butImg.visibility=View.GONE
            }

            updateMarker(it)
            var latStart:LatLng? =null
            //算出总距离
            try {

            if(null==it.technicianStatus){
                 latStart =
                    LatLng(it.technicianStartLatitude.toDouble(), it.technicianStartLongitude.toDouble())
            }else{
                 latStart =
                    LatLng(it.technicianLatitude.toDouble(), it.technicianLongitude.toDouble())
            }

            latEnd = LatLng(it.latitude.toDouble(), it.longitude.toDouble())

            var s1 = DistanceUtil.getDistance(latStart, latEnd) / 1000

            z_distance = DecimalUtils.getNumber(s1).toDouble()

            binding.tvDistance.text = "距离你" + z_distance + "km"
            binding.progress.progress = 0
            Log.e("-max-", "max1= " + z_distance)

            Log.e("-max-", "max1= " + DecimalUtils.getNoCarry(z_distance).toInt())
            binding.progress.max = DecimalUtils.getNoCarry(z_distance).toInt()

            //去开启连续定位
            //获取一次定位todo:
            handler.sendEmptyMessageDelayed(0x101, 1000)
            }catch (e:Exception){

            }

        }

        vm.type.observe(this) {

            if (it == "1") {//添加
                lifecycleScope.launch {
                    if (PermissionManager.requestPermissions(
                            this@OrderDetailsActivity, 1000,
                            Manifest.permission.CAMERA,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE
                        ) is PermissionResult.PermissionGranted
                    ) {

                        if (vm.nopath.size < 3) {
                            ChosePhotoUtils.getChosePhoto(context(), 3 - vm.nopath.size)
                        } else {
                            toast("最多选三张")
                        }

                    }

                }
            }

        }



    }

    private val handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            setLongLocation()
        }
    }


    fun initAdapter() {

        val attachement: java.util.ArrayList<GoodsImgBean> = java.util.ArrayList<GoodsImgBean>()

        val bean = GoodsImgBean(-1, "", -1, false)
        attachement.add(bean)

        val left = UiUtils.dp2Px(context(), 3f)
        val itemDecoration: RecyclerView.ItemDecoration = object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                super.getItemOffsets(outRect, view, parent, state)
                val childAdapterPosition = parent.getChildAdapterPosition(view)
                val i = childAdapterPosition % 3
                if (i != 0) {
                    outRect.left = left
                }
                outRect.top = left
            }
        }
        recordAdapter = OrderImgAdapter(vm, attachement)

        binding.recyclerView.addItemDecoration(itemDecoration)
        binding.recyclerView.adapter = recordAdapter

    }


    private fun initMap(latitude: String, longitude: String) {
        mMapView = binding.mapview
        if (null == mMapView) {
            return
        }
        mBaiduMap = mMapView?.map
        if (null == mBaiduMap) {
            return
        }

        // 使得圆角地图情况下，地图log不会被遮盖
        mBaiduMap?.setViewPadding(30, 0, 30, 20)

        // 设置初始中心
        val start = LatLng(latitude.toDouble(), longitude.toDouble())
        val mapStatusUpdate = MapStatusUpdateFactory.newLatLngZoom(start, 12f)
        mBaiduMap?.setMapStatus(mapStatusUpdate)

    }


    private var mMarker: Marker? = null

    /**
     * 更新marker状态
     */
    private fun updateMarker(bean: TechOrderDetail) {

        //设置用户的位置  icon_binding_point  icon_start_custom
        mBitmapDescriptorStart = BitmapDescriptorFactory.fromResource(R.drawable.icon_binding_point)


        val start = LatLng(bean.technicianLatitude.toDouble(), bean.technicianLongitude.toDouble())

         var markerOptions = MarkerOptions()
            .position(start)
            .icon(mBitmapDescriptorStart)
//        mBaiduMap?.addOverlay(markerOptions)

        mMarker = mBaiduMap!!.addOverlay(markerOptions) as Marker


        val inflate: View =
            LayoutInflater.from(this@OrderDetailsActivity).inflate(R.layout.map_view, null)
        var img = inflate.findViewById<QMUIRadiusImageView>(R.id.img)
        if (null != bean.headImage && !TextUtils.isEmpty(bean.headImage)) {

            Glide.with(this@OrderDetailsActivity)
                .asBitmap()
                .load(bean.headImage)
                .into(object : SimpleTarget<Bitmap>() {
                    override fun onResourceReady(
                        resource: Bitmap,
                        transition: Transition<in Bitmap>?
                    ) {
                        img.setImageBitmap(resource)
                        val end = LatLng(bean.latitude.toDouble(), bean.longitude.toDouble())
                        val markerOptions1 = MarkerOptions()
                            .position(end)
                            .icon(BitmapDescriptorFactory.fromView(inflate))
                        mBaiduMap?.addOverlay(markerOptions1)


                    }
                })


        }


    }

    override fun onResume() {
        super.onResume()
        if (null != mMapView) {
            mMapView?.onResume()
        }

    }

    override fun onPause() {
        super.onPause()
        if (null != mMapView) {
            mMapView?.onPause()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            handler.removeMessages(0x101)
//
//            if (null != mMapView) {
//                mMapView!!.onDestroy()
//                mBaiduMap?.clear()
//            }
//
//            if (null != mBitmapDescriptorStart) {
//                mBitmapDescriptorStart?.recycle()
//            }
//            if (null != locationClient) {
//                locationClient?.stop()
//                locationClient = null
//            }
            finish()
            return true
        }
        return false
    }


    override fun onDestroy() {
        super.onDestroy()

        handler.removeMessages(0x101)

        if(null!=mMarker) {
            mMarker?.cancelAnimation()
        }
        if (null != mMapView) {
            mMapView!!.onDestroy()
            mBaiduMap?.clear()
        }
        if (null != mBitmapDescriptorStart) {
            mBitmapDescriptorStart?.recycle()
        }
        if (null != locationClient) {
            locationClient?.stop()
            locationClient = null
        }

    }


    override fun listeners() {
        super.listeners()
        binding.butCancel.onClick {
            PopuCancelUtils.show(context(), binding.butCancel, object : ChoiceData {
                override fun onRestuse(id: String?) {
                    //todo 同意取消订单
                }

            })
        }

        binding.llPhone.onClick {

            //拨打电话
            launch {
                val requestPermissions = PermissionManager.requestPermissions(
                    this@OrderDetailsActivity, 1000, Manifest.permission.CALL_PHONE
                )
                if (requestPermissions is PermissionResult.PermissionGranted) {
                    //拨打电话
                    vm.bean.value?.phone?.let {
                        DialUtils.dialPhone(context(), it)
                    }
                }
            }
        }


    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) {
            return
        }
        if (requestCode == MIntentAction.REQUEST_CODE_IMG) {//图片

            val selectList = PictureSelector.obtainMultipleResult(data)
            val list = ArrayList<String>()
            if (null != selectList) {
                for (item in selectList) {

                    if (item.path.contains("content://")) {

                        val cr = this.contentResolver
                        list.add(FileUtils.getFilePathFromContentUri(item.path.toUri(), cr))
                    } else {
                        list.add(item.path)
                    }

//                    //添加一个默认
//                    val bugAttachment = GoodsImgBean(0, "", 0, true)
//                    recordAdapter!!.addData(recordAdapter!!.data.size - 1, bugAttachment)
//                    vm.nopath.add("")
                }

                Log.e("-hhhh-", "list="+list.size )


                OssUtils(this, vm)
                    .setUpLoad("img", list, this)

            }

            return


        }

        if (requestCode == MIntentAction.REQUEST_CODE_CAMERA) {//拍照
            //拍照
            val selectList = PictureSelector.obtainMultipleResult(data) ?: return
            val list = ArrayList<String>()
            if (selectList[0].path.contains("content://")) {

                val cr = this.contentResolver
                list.add(FileUtils.getFilePathFromContentUri(selectList[0].path.toUri(), cr))

            } else {
                list.add(selectList[0].path)
            }
//            if(vm.type==5){
//                //添加一个默认
//                val bugAttachment = GoodsImgBean(0, "", 0, true)
//                recordAdapter!!.addData(recordAdapter!!.data.size - 1, bugAttachment)
//                vm.nopath.add("")
//            }
            OssUtils(this, vm)
                .setUpLoad("img", list, this)


        }

        return


    }


    override fun onUploadSuccess(t: UpImgBean) {

        if (null != t.url) {
            val bugAttachment = GoodsImgBean(0, t.url!!, 0, false)
            recordAdapter!!.addData(recordAdapter!!.data.size - 1, bugAttachment)
            vm.nopath.add(t.url!!)
        }
    }

    override fun onUploadError(error: String?) {
    }


    override fun vmClass(): Class<OrderDetailsVModel> {
        return OrderDetailsVModel::class.java
    }

    override fun binding(): ActivityOrderDetailsBinding {
        return ActivityOrderDetailsBinding.inflate(layoutInflater)
    }

    override fun title(): String? {
        return "订单详情"
    }

    //一次定位
    private var locationClient: LocationClient? = null


    fun setLongLocation() {
        locationClient = LocationClient(context())
        // 设置定位条件
        val option = LocationClientOption()

        option.setIsNeedLocationPoiList(true) //获取附近 poi

//        option.setIsNeedLocationDescribe(true); //位置语义化
        option.isOpenGps = true // 是否打开GPS

        option.setCoorType("bd09ll") // 设置返回值的坐标类型

//        option.setScanSpan(5000) // 设置定时定位的时间间隔。单位毫秒
//        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setAddrType("all")
        option.setIgnoreKillProcess(false) //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.setOnceLocation(true)

        locationClient?.locOption = option

        locationClient?.registerLocationListener(object : BDAbstractLocationListener() {
            override fun onReceiveLocation(amapLocation: BDLocation?) {
                if (null != amapLocation) {


                    try {
                        var latStart =
                            LatLng(amapLocation.latitude, amapLocation.longitude)

                        var s1 = DistanceUtil.getDistance(latStart, latEnd) / 1000

                        var distance = DecimalUtils.getNumber(s1).toDouble()

                        binding.tvDistance.text = "距离你" + distance + "km"

                        Log.e("-tvDistance-", "distance=" + distance)

                        //走了多少距离
                        var s2 = z_distance - distance

                        Log.e("-max-", "max3= " + z_distance)

                        Log.e("-max-", "max2= " + DecimalUtils.getNoCarry(s2).toInt())

                        binding.progress.progress = DecimalUtils.getNoCarry(s2).toInt()
                        //移动market

                        mMarker?.position = latStart
//                        val mapStatusUpdate = MapStatusUpdateFactory.newLatLng(latStart)
//                        mBaiduMap!!.setMapStatus(mapStatusUpdate)

//                        val transformation = Transformation(mMarker?.position, latStart)
//
//                        mMarker?.setAnimation(transformation);
//                        mMarker?.startAnimation();

                        //清除

//
//                        var  markerOptions = MarkerOptions()
//                            .position(latStart)
//                            .icon(mBitmapDescriptorStart)
//                        mBaiduMap?.addOverlay(markerOptions)
//                        mMarker = mBaiduMap!!.addOverlay(markerOptions) as Marker



                    } catch (e: Exception) {

                    }


                }

                handler.sendEmptyMessageDelayed(0x101, 3000)

            }
        })
        locationClient?.locOption = option

        locationClient?.start()

    }


}
